from django.shortcuts import render
from django.shortcuts import render
import json
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.conf import settings
import os


# Create your views here.
from .serializers import *
from rest_framework import viewsets
from .models import *


from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend, CharFilter

from django_filters import FilterSet, DateFilter

from django.utils.timezone import make_aware
from datetime import datetime, timedelta

from django.http import HttpResponse
from datetime import datetime

# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.schemas import AutoSchema, coreapi
import coreschema

# from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from coreapi import Field
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import F


# Create your views here.
class temperature_Sj1(APIView):
    # 设置默认的每页数据量
    page_size = 10

    schema = AutoSchema(
        manual_fields=[
            Field(
                name="id",
                required=False,
                location="query",
                schema=coreschema.Number(description="id"),
            ),
            Field(
                name="xgateway",
                required=False,
                location="query",
                schema=coreschema.String(description="xgateway"),
            ),
            Field(
                name="xtagname",
                required=False,
                location="query",
                schema=coreschema.String(description="xtagname（区域标签名）"),
            ),
            Field(
                name="xvalue",
                required=False,
                location="query",
                schema=coreschema.String(description="xvalue（温度值）"),
            ),
            Field(
                name="xquality",
                required=False,
                location="query",
                schema=coreschema.String(description="xquality"),
            ),
            Field(
                name="xtimestamp",
                required=False,
                location="query",
                schema=coreschema.String(description="xtimestamp（时间）"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="（开始时间，格式示例：2024-07-10 16:34:42）"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="（结束时间，格式示例：2024-07-12 16:39:43）"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = temperature_Sj1_Serializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = Sj1.objects.using("temperature").filter().order_by("xtimestamp")
        # 获取请求的参数
        id = request.query_params.get("id")
        xtagname = request.query_params.get("xtagname")
        xvalue = request.query_params.get("xvalue")
        xtimestamp = request.query_params.get("xtimestamp")
        # 请求开始-结束时间
        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = Sj1.objects.using("temperature").filter(id=id)
        if xtagname is not None:
            queryset = queryset.filter(xtagname__contains=xtagname)
        if xvalue is not None:
            queryset = queryset.filter(xvalue=xvalue)
        if xtimestamp is not None:
            queryset = queryset.filter(xtimestamp=xtimestamp)
        if start_time_param is not None and end_time_param is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            queryset = queryset.filter(
                xtimestamp__gte=start_time_param_trans, xtimestamp__lte=end_time_param_trans
            )

        return queryset
